package com.example.simplenet;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.PowerManager;
import android.util.Log;

public class Alarm extends BroadcastReceiver {
	
	private static ConnectionMan mService;
	private static PowerManager.WakeLock mWl = null;
	
	private static PendingIntent mPendingIntent = null;
	private static boolean mAlarmIsSet = false;
	
	private static String TAG = "ALARM";
	
	@SuppressLint("Wakelock")
	@Override
	public void onReceive(Context context, Intent intent) {
	
		Log.i("ALARM", "onReceive");
		if (!mAlarmIsSet)
			cancelAlarm(context);
		else {
			if (mWl != null)
				mWl.release();
			PowerManager powerManager = (PowerManager) context
					.getSystemService(Context.POWER_SERVICE);
			mWl = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
			Log.i(TAG, "Wakelock aquired");
			mWl.acquire();
			
			mService.reloadPage();
		}
	}
	
	public void handlingDone() {
	
		if (mWl != null) {
			Log.i(TAG, "Wakelock released");
			mWl.release();
			mWl = null;
		}
	}
	
	public void setAlarm(ConnectionMan service) {
	
		mService = service;
		Intent intent = new Intent("com.example.simplenet.RELOAD_PAGE");
		mPendingIntent = PendingIntent.getBroadcast(service, 0, intent, 0);
		AlarmManager alarmManager = (AlarmManager) service
				.getSystemService(Context.ALARM_SERVICE);
		alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
				System.currentTimeMillis() + 60000, 60000, mPendingIntent); // Millisec *
																// Second *
																// Minute
		mAlarmIsSet = true;
		Log.i("ALARM", "Alarm is set!");
	}
	
	public void cancelAlarm(Context context) {
		AlarmManager alarmManager = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		alarmManager.cancel(mPendingIntent);
		mAlarmIsSet = false;
		Log.i("ALARM", "Alarm cancelled");
		handlingDone();
	}
	
	public static class NetworkStateChangeListener extends BroadcastReceiver {
		
		@Override
		public void onReceive(Context context, Intent intent) {
		
			ConnectivityManager connectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivityManager.getActiveNetworkInfo() != null)
				Log.i("TAG", (connectivityManager.getActiveNetworkInfo()
						.isConnected() ? "Connected. " : "Disconnected. ")
						+ connectivityManager.getActiveNetworkInfo()
								.getTypeName());
			else
				Log.i("TAG", "no connection");
		}
		
	}
}
